package com.dianrui.firemenmonitor.util;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;

import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.dianrui.firemenmonitor.dialog.FlycoDialog.listener.OnOperItemClickL;
import com.dianrui.firemenmonitor.dialog.FlycoDialog.widget.ActionSheetDialog;
import com.dianrui.firemenmonitor.view.Immersion.EyesKitKat;
import com.dianrui.firemenmonitor.view.Immersion.EyesLollipop;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;


public class MyUtil {

    private static Stack<Activity> mActivities = new Stack<>();
    private static MyUtil instance = null;

    public static MyUtil getInstance() {
        if (null == instance) {
            synchronized (MyUtil.class) {
                if (null == instance) {
                    instance = new MyUtil();
                }
            }
        }
        return instance;
    }

    //检查GPS是否开启
    public static  boolean isGpsEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    //点下出动画
    public static void initViewAnimation(final View showView, boolean isshow, boolean istop) {

        float[] up2down;

        float[] down2up;

        if (istop) {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{0.0f, 0.0f};

        } else {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{1.0f, 0.0f};
        }

        if (isshow) {
            TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    down2up[0], Animation.RELATIVE_TO_SELF, down2up[1]);
            mShowAction.setDuration(500);
            showView.clearAnimation();
            showView.startAnimation(mShowAction);
        } else {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, up2down[0], Animation.RELATIVE_TO_SELF, up2down[1]);
            mHiddenAction.setDuration(500);
            mHiddenAction.setAnimationListener(new Animation.AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    showView.setVisibility(View.GONE);
                    showView.invalidate();
                }
            });

            showView.clearAnimation();
            showView.startAnimation(mHiddenAction);
        }
    }


    public static void initViewDownAnimation(final View showView, boolean isshow, boolean istop) {

        float[] up2down;

        float[] down2up;

        if (istop) {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{0.0f, 1.0f};

        } else {
            up2down = new float[]{0.0f, 0.0f};
            down2up = new float[]{1.0f, 0.0f};
        }

        if (isshow) {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, up2down[0], Animation.RELATIVE_TO_SELF, up2down[1]);
            mHiddenAction.setDuration(100);
            mHiddenAction.setAnimationListener(new Animation.AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    showView.setVisibility(View.INVISIBLE);
                    showView.invalidate();
                }
            });

            showView.clearAnimation();
            showView.startAnimation(mHiddenAction);
        } else {
            TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    down2up[0], Animation.RELATIVE_TO_SELF, down2up[1]);
            mShowAction.setDuration(400);
            showView.clearAnimation();
            showView.startAnimation(mShowAction);
        }
    }

    public static MapStatusUpdate setLatLngBounds(List<LatLng> points, MapView mMapView) {
        LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
        for (LatLng p : points) {
            builder2 = builder2.include(p);
        }
        LatLngBounds latlngBounds = builder2.build();
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(latlngBounds, mMapView.getWidth(), mMapView.getHeight());
        return u;
    }

    public static String getAppInfo(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = context.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return  versionName;
        } catch (Exception e) {
        }
        return null;
    }

    public static Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }


    //获取手机型号
    public static String getSystemModel() {
        return Build.MODEL;
    }

    //   获取手机品牌
    public static String getSystemBARND() {
        return Build.BRAND;
    }

    @SuppressLint("HardwareIds")
    public static String getUniqueId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    /**
     * 判断应用是否在后台
     *
     * @param context
     * @return
     */
    public static boolean isAppIsInBackground(Context context) {

        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

    /**
     * 计算两个gps间的距离
     *
     * @param a
     * @param b
     * @param c
     * @param d
     * @return 返回单位为计算好的千米
     */
    public static String gpsToDistanceKM(double a, double b, double c, double d) {
        DecimalFormat df = new DecimalFormat("######0.00");
        float[] results = new float[1];
        Location.distanceBetween(a, b, c, d, results);
        return df.format(Double.valueOf(results[0] / 1000));
    }


    /**
     * 计算两点之间距离
     * @param start
     * @param end
     * @return 米
     */
    public static Double getDistance(LatLng start, LatLng end){
        double lon1 = (Math.PI / 180) * start.longitude;
        double lon2 = (Math.PI / 180) * end.longitude;
        double lat1 = (Math.PI / 180) * start.latitude;
        double lat2 = (Math.PI / 180) * end.latitude;

        // 地球半径
        double R = 6371;

        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))
                * R;

        return d*1000;

    }

    public static LatLng pianyi(double lon,double lat)
    {
        double x = lon; double y = lat;
        double z = Math.sqrt(x*x+y*y) + 0.00002*Math.sin(y*Math.PI) ;
        double temp =Math.atan2(y, x)  + 0.00004  * Math.cos(x*Math.PI);

        double bdLon = z * Math.cos(temp) + 0.0081;
        double bdLat = z * Math.sin(temp) + 0.008;
        LatLng newcenpt = new LatLng(bdLat, bdLon);
        return newcenpt;
    }







    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }




    /*** 判断网络情况   有网络返回true，没网络返回false*/
    public static boolean isNetworkAvalible(Context context) {
        //检测API是不是小于23，因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //获得ConnectivityManager对象
            android.net.ConnectivityManager connMgr = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取WIFI连接的信息
            android.net.NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(android.net.ConnectivityManager.TYPE_WIFI);
            //获取移动数据连接的信息
            android.net.NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(android.net.ConnectivityManager.TYPE_MOBILE);
            //无线网连接和数据网连接都断开
            if (!wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
                return false;
            }
            //无线网连接和数据网连接一个
            return true;
            //API大于23时使用下面的方式进行网络监听
        } else {
            // 获得网络状态管理器
            android.net.ConnectivityManager connectivityManager = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                return false;
            } else {
                // 建立网络数组
                android.net.NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();
                if (net_info != null) {
                    for (int i = 0; i < net_info.length; i++) {
                        // 判断获得的网络状态是否是处于连接状态
                        if (net_info[i].getState() == android.net.NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
    public static int getAppVersionCode(Context context) {
        return getAppVersionCode(context, context.getPackageName());
    }
    /**
     * 获取App版本码
     *
     * @param context     上下文
     * @param packageName 包名
     * @return App版本码
     */
    public static int getAppVersionCode(Context context, String packageName) {
        if (isSpace(packageName)) return -1;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? -1 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static boolean isSpace(String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    public static String getAppVersionName(Context context) {
        return getAppVersionName(context, context.getPackageName());
    }

    public static String getAppVersionName(Context context, String packageName) {
        if (isSpace(packageName)) return null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            return pi == null ? null : pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void createPhotoChooseDialog(final int requestCode, final int maxSize, final Context context, final FunctionConfig functionConfig, final GalleryFinal.OnHanlderResultCallback listener) {
        String[] stringItems = {"拍照", "相册选取"};
        final ActionSheetDialog dialog = new ActionSheetDialog(context, stringItems, null)
                .isTitleShow(false)
                .itemTextColor(Color.parseColor("#000000"))
                .setmCancelBgColor(Color.parseColor("#FFFFFF"))
                .cancelText(Color.BLACK);
        dialog.title("选择您的方式");
        dialog.titleTextSize_SP(14f).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        GalleryFinal.openCamera(requestCode, functionConfig, listener);
                        dialog.dismiss();
                        break;
                    case 1:
                        GalleryFinal.openGalleryMuti(requestCode, maxSize, listener);
                        dialog.dismiss();
                        break;

                }
            }
        });

    }

    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }



    private static boolean isInstallMaps(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        List<String> packageNames = new ArrayList<>();
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public synchronized void removeActivity(Activity activity) {
        if (mActivities.contains(activity)) {
            mActivities.remove(activity);
        }
    }

    public synchronized void clear() {
        int index = size()-1;
        while (index>=0){
            Activity activity = mActivities.pop();
            removeActivity(activity);
            activity.finish();
            index--;
        }
    }

    public int size() {
        return mActivities.size();
    }


    public static String formatBy2Scale(Double doubleVal, int scale) {
        if (null == doubleVal) {
            doubleVal = new Double(0);
        }
        StringBuffer sbStr = new StringBuffer("0");
        for (int i = 0; i < scale; i++) {
            sbStr.append("0");
        }
        DecimalFormat myformat = new DecimalFormat(sbStr.toString());
        return myformat.format(doubleVal);
    }

    public static String formatBy2Float(Float floatVal, int scale) {
        if (null == floatVal) {
            floatVal = new Float(0);
        }
        StringBuffer sbStr = new StringBuffer("0.");
        for (int i = 0; i < scale; i++) {
            sbStr.append("0");
        }
        DecimalFormat myformat = new DecimalFormat(sbStr.toString());
        return myformat.format(floatVal);
    }

    /**
     * 状态栏变色
     *
     * @param activity
     * @param color
     */
    public static void setStatusBarLightMode(Activity activity, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否为小米或魅族手机，如果是则将状态栏文字改为黑色
            if (MIUISetStatusBarLightMode(activity, true) || FlymeSetStatusBarLightMode(activity, true)) {
                //设置状态栏为指定颜色
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
                    activity.getWindow().setStatusBarColor(color);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
                    //调用修改状态栏颜色的方法
                    setStatusBarColor(activity, color);
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //如果是6.0以上将状态栏文字改为黑色，并设置状态栏颜色
                activity.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                activity.getWindow().setStatusBarColor(color);

                //fitsSystemWindow 为 false, 不预留系统栏位置.
                ViewGroup mContentView = (ViewGroup) activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
                View mChildView = mContentView.getChildAt(0);
                if (mChildView != null) {
                    mChildView.setFitsSystemWindows(true);
                    ViewCompat.requestApplyInsets(mChildView);
                }
            }
        }
    }

    /**
     * 状态栏变色高亮（文字白色）
     *
     * @param activity
     * @param statusColor
     */
    public static void setStatusBarColor(Activity activity, int statusColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            EyesLollipop.setStatusBarColor(activity, statusColor);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            EyesKitKat.setStatusBarColor(activity, statusColor);
        }
    }

    /**
     * MIUI的沉浸支持透明白色字体和透明黑色字体
     * https://dev.mi.com/console/doc/detail?pId=1159
     */
    static boolean MIUISetStatusBarLightMode(Activity activity, boolean darkmode) {
        Window window = activity.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        boolean result = false;
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            result = true;
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格，Flyme4.0以上
     */
    static boolean FlymeSetStatusBarLightMode(Activity activity, boolean darkmode) {
        boolean result = false;
        try {
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (darkmode) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            activity.getWindow().setAttributes(lp);
            result = true;
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return result;
    }


    public static String patternCode(String smsBody) {
        String regex=new String("(\\d{4})");
        String smsCode="";
        Pattern pattern=Pattern.compile(regex);
        Matcher matcher=pattern.matcher(smsBody);
        while (matcher.find()){
            smsCode=matcher.group(0);
        }
        Log.e("patternCode------>", smsCode);
        return  smsCode;
    }



    public static  String getDynamicPwd(String content) {

        // 此正则表达式验证六位数字的短信验证码

        Pattern pattern = Pattern.compile("(?<![0-9])([0-9])(?![0-9])");

        Matcher matcher = pattern.matcher(content);

        String dynamicPwd = "";

        while (matcher.find()) {

            dynamicPwd = matcher.group();

            Log.i("TAG", "getDynamicPwd: find pwd=" + dynamicPwd);
        }
        return dynamicPwd;
    }



    public static Activity getActivity(Context context) {
        while (!(context instanceof Activity) && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
        }
        if (context instanceof Activity) {
            return (Activity) context;
        }else {
            return null;
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String getUserDate(String sformat) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
        String dateString = formatter.format(currentTime);
        return dateString;
    }


}
